package com.meixiang.activity.account.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.SelectMemberStoreActivity;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.DesUtil;
import com.meixiang.view.ClearEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * yangdecheng 第三方手机绑定
 * Created by ydc on 2016/9/12.
 */

public class BindingAccountActivity extends BaseActivity {


    /**
     * 手机号
     */
    @Bind(R.id.edtTxt_phone)
    ClearEditText mCetInputName;
    /**
     * 验证码按钮
     */
    @Bind(R.id.tv_verification)
    TextView mTvVerification;
    /**
     * 验证码
     */
    @Bind(R.id.cet_yzm)
    ClearEditText mCetVerificationCode;
    /**
     * 确定
     */
    @Bind(R.id.tv_register)
    TextView mTvRegister;

    @Bind(R.id.tv_userName)
    TextView  tvuserName;



    @Bind(R.id.tv_yzmtitle)
    TextView  tv_yzmtitle;

    @Bind(R.id.tv_weixinname)
    TextView   tv_weixinname;



    private Activity mActivity;

    private String  userName;
    private String openid;
    private UserInfo mUserInfo;
    private  String platformStr;



    //短信验证码
    CountDownTimer regetTimer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTvVerification.setText((millisUntilFinished / 1000) + "(S)");
            mTvVerification.setEnabled(false);
        }

        @Override
        public void onFinish() {
            mTvVerification.setText("验证");
            mTvVerification.setEnabled(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_bindingaccount_layout);


        ButterKnife.bind(this);
        mActivity = BindingAccountActivity.this;
        super.onCreate(savedInstanceState);


        userName=getIntent().getStringExtra("username");
        tvuserName.setText(userName);
        openid=getIntent().getStringExtra("openid");
        platformStr=getIntent().getStringExtra("platformStr");

        tv_weixinname.setText("尊敬的"+platformStr+"用户：");

    }

    @Override
    protected void initTitle() {
        setTitle("绑定账号");


    }

    @Override
    protected void initView() {
    }

    @Override
    protected void setData() {

    }


    /**
     * 获取短信验证
     */
    private void sendVerificationCode() {
        HttpParams params = new HttpParams();
        params.put("mobile", mCetInputName.getText().toString());
        HttpUtils.post(Config.REGISTER_SEND_CODE_NEW, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                regetTimer.start();
                AbToastUtil.showToast(mActivity, message);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(mActivity, message);
                //tv_yzmtitle.setText("验证失败");
            }
        });
    }


    /**
     * 验证码验证
     */
    private void verificationCode(String VerificationCode) {
        HttpParams params = new HttpParams();
        params.put("mobile", mCetInputName.getText().toString());
        params.put("mobileCode", VerificationCode);
        HttpUtils.post(Config.checkValidCode_URL_NEW, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
               /* regetTimer.start();
                AbToastUtil.showToast(mActivity, message);*/
                tv_yzmtitle.setText("验证成功");
                bindPhone(mCetInputName.getText().toString().trim(),openid);
            }

            @Override
            public void onError(String code, String message) {
               // AbToastUtil.showToast(mActivity, message);
                tv_yzmtitle.setText(message);
            }
        });
    }

    @OnClick({R.id.tv_verification, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_verification:
                if ((mCetInputName.getText().toString().length()) != 11) {
                    Tool.showTextToast(mActivity, "请输入11位手机号码");
                    return;
                }
                sendVerificationCode();
                break;
            case R.id.tv_register:

                if (mCetInputName.getText().toString().trim().length() > 16) {
                    Tool.showTextToast(mActivity, "密码不能小于6~16位");
                    return;
                }
                if (TextUtils.isEmpty(mCetVerificationCode.getText().toString())) {
                    Tool.showTextToast(mActivity, "请输入验证码");
                    return;
                }

                verificationCode(mCetVerificationCode.getText().toString());
                //bindPhone(mCetInputName.getText().toString().trim(),openid);

                //verificationCode(mCetVerificationCode.getText().toString());
                break;
        }
    }


    /**
     * 手机绑定
     */
    private void bindPhone(String phone,String openid) {
        HttpParams params = new HttpParams();
        params.put("phone", phone);
        params.put("openid",openid);

        //http://192.168.0.21:8080/maxmind-api/thirdlogin/bindPhone

        HttpUtils.post(Config.bindPhone_URL, params, new HttpCallBack(mActivity,"正在登录中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                String openid="";
                String codeStr="";
                String sessionId="";
                String memberCardNum="";

                if( code.equals("0")){
                    sessionId= result.optString("sessionId");
                    memberCardNum=result.optString("memberCardNum");
                    HashMap<String, String> vals = new HashMap<String, String>();
                    vals.put("jsessionid", sessionId);
                    MXApplication.mApp.getSession().set(vals);
                    AbToastUtil.showToast(BindingAccountActivity.this, message);

                    if (Integer.parseInt(memberCardNum) > 1) {
                        startActivity(new Intent(context, SelectMemberStoreActivity.class));
                    } else {
                        getUserinfo();
                        startActivity(MainActivity.class);
                    }
                    finish();
                }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(BindingAccountActivity.this, message);
            }
        });


    }


    /**
     * 登录成功获取用户信息保存并且用户信息
     */
    private void getUserinfo() {
        HttpParams params = new HttpParams();

        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mUserInfo = AbJsonUtil.fromJson(result.toString(), UserInfo.class);
                MXApplication.mApp.setUser(mUserInfo);

                Log.e("TAG", "得到当前用户信息==" + MXApplication.mApp.getUser());

            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        regetTimer.cancel();
    }
}
